/*!
 * 通用登录模块
 * @author Sherlock 
 * --------------------------
 * refresh 登陆后是否自动刷新
 * loginCallback 登录的回调数组
 * addLoginCallback 见下面注释
 * refreshUserInfo 刷新右上角用户信息
 * loginSuccessAndContinue 已过时的回调方法
 * loginedCallback 同上
 */
require( './style.less' );
define( [
  'jquery',
  'require',
  'bootstrap',
  'jqueryFrom',
  'bigwe_utils',
  'startNotice',
  'constants',
  'api',
], function( $, require ) {
  'use strict';

  var constants = require( 'constants' ),
    interFace = require( 'api' );
  var returnParam = {
    refresh: false,
    loginCallback: [],
    /**
     * 添加一个回调函数到数组，登陆后按添加顺序执行
     */
    addLoginCallback: function( fn ) {
      if ( $.isFunction( fn ) ) {
        return this.loginCallback.push( fn ) - 1;
      }
    }
  };
  var bu = require( 'bigwe_utils' );
  var $self = returnParam.$selector = $( '#login-modal' );
  var loginLogo = '';
  var loginAccount = '';

  // 登陆后去的页面
  var backUrl = bu.getUrlParam( location.href, 'backUrl' ),
    currentUrl = bu.getUrlParam( location.href, 'currentUrl' );

  for ( var i = 0; i < document.cookie.split( '; ' ).length; i++ ) {
    loginLogo = document.cookie.split( '; ' )[ i ].split( '=' )[ 0 ];
    if ( loginLogo.indexOf( 'login' ) >= 0 ) {
      $( '#username' ).val( getCookie( loginLogo ) );
      $( '#rememberMe' ).attr( 'checked', 'checked' );
    }
  }
  $( '#username' ).change( function() {
    var k = 0;
    for ( var j = 0; j < document.cookie.split( '; ' ).length; j++ ) {
      loginAccount = document.cookie.split( '; ' )[ j ].split( '=' )[ 1 ];
      if ( $( '#username' ).val() != loginAccount ) {
        k++;
      }
    }
    if ( k == document.cookie.split( '; ' ).length ) {
      $( '#rememberMe' ).removeAttr( 'checked' );
    } else {
      $( '#rememberMe' ).prop( 'checked', 'checked' );
    }
  } );

  $( '.loginAction' ).on( 'click tap', function() {
    //window.top.location.href = $(this).attr('_href');
    window.top.open( $( this ).attr( 'open-url' ), 'qqlogin', 'height=500,width=800,top=120,left=' + ( window.screen.availWidth / 2 - 400 ) + ',help=no,resizable=no,status=no,scroll=no' );
  } );
  $( '.js_otherLogin' ).each( function() {
    $( this ).attr( '_href', $( this ).attr( '_href' ) + '&backUrl=' + escape( window.top.location.href ) );
  } );

  var refreshUserInfo = returnParam.refreshUserInfo = function( obj ) {
    var $logined = $( '.header_container_main  .status.status_enter', window.top.document );
    var $frm_header = $( '#frm_header', window.top.document );
    // 用户头像
    $( '.js_face_img', $logined ).prop( 'src', obj.head_img_url || '/Public/static/images/default_user_face.png' );
    // 用户昵称
    $( '.js_user_nickname', $logined ).prop( 'title', obj.user_nicename || '' ).text( obj.user_nicename || '' );
    // 用户id
    $( '.logout', $logined ).prop( 'href', $( '.logout', $logined ).attr( 'href' ) + obj.user_id );
    // 用户是否是第三方登录
    if ( obj.login_type == 'oauth' ) {
      // 第三方登录需要绑定微知号
      $( '.js_oauth_modal' ).addClass( 'js_register_guide' );
      $( '#register-guide' ).modal( 'show' );
    } else {
      $( '.js_oauth_modal' ).removeClass( 'js_register_guide' );
    }
    // 页面信息和user_login
    var userId = obj.user_id || '';
    var userLogin = obj.user_login || '';
    var pageId = obj.page_info && obj.page_info.select;
    var pageName = obj.page_info && obj.page_info.name;
    $( '#user-id-bg', $frm_header ).val( userId );
    $( '#user_login', $frm_header ).val( userLogin );
    // page_id
    $( '#page_id', $frm_header ).val( pageId );
    // page_name
    $( '#page_name', $frm_header ).val( pageName );
    // 更新用户信息
    $.extend( constants, {
      userId: userId,
      userLogin: userLogin,
      pageId: pageId,
      pageName: pageName
    } );

  };

  var loginSuccessAndContinue = returnParam.loginSuccessAndContinue = null;

  var loginSuccessAsync = window.loginSuccessAsync = returnParam.loginSuccessAsync = function( obj ) {
    // 登录成功后异步刷新用户信息
    $self.removeClass( 'fade' ).modal( 'hide' ).addClass( 'fade' );
    if ( returnParam.refresh ) {
      window.top.location.reload();
    } else {
      // startNotice
      require( 'startNotice' )( obj.user_login );
      var $header = document.body;
      var $logined = $( '.status.status_enter', $header );
      $( '#login-btn', $self ).text( '登录' ).removeAttr( 'disabled' );
      $( '#loginform', $self )[ 0 ].reset();

      // 登录限制取消
      $( '.js_unlogin_forward', document ).off( 'click.js_unlogin_forward' ).removeClass( 'js_unlogin_forward' );

      refreshUserInfo( obj );

      $logined.removeClass( 'hide' );

      $( '.status.status_outer', $header ).addClass( 'hide' );

      if ( $.isFunction( returnParam.loginSuccessAndContinue ) ) {
        returnParam.loginSuccessAndContinue();
        delete returnParam.loginSuccessAndContinue;
      }

      for ( var i in returnParam.loginCallback ) {
        returnParam.loginCallback[ i ].call( $self, obj );
      }

      if ( !returnParam.refresh && $.isFunction( returnParam.loginedCallback ) ) {
        returnParam.loginedCallback();
      }
    }
  };
  $( '#loginform', $self ).submit( function() {
    $( '#login-btn', $self ).text( '登录中...' ).prop( 'disabled', 'disabled' );
    $.ajax( {
      type: 'post',
      url: interFace.LOGIN,
      data: $( '#loginform' ).serialize() + '&page_info=' + location.pathname,
      success: function( data ) {
        var obj = $.parseJSON( data );

        if ( obj.state === '1' || obj.state === '0' ) {

          $( '#error_msg' ).html( obj.msg );
          $( '#login-btn' ).text( '登录' ).removeAttr( 'disabled' );
          if ( obj.state === '1' ) {
            // 设置选中文本
            $( '#username', $self )[ 0 ].select();
          } else if ( obj.state === '0' ) {
            $( '#password', $self )[ 0 ].select();
          }

        } else if ( obj.state === '2' ) {

          $( '#frm_header #user_login', window.top.document ).val( obj[ 'user_login' ] );

          if ( obj[ 'forward' ] ) {
            window.top.location.href = obj[ 'forward' ];
          } else {
            if ( backUrl && currentUrl ) {
              window.location.href = backUrl;
            } else if ( backUrl && !currentUrl ) {
              window.top.location.href = backUrl;
            } else {
              loginSuccessAsync( obj );
            }
          }
        }
      },
      error: function() {
        $( '#login-btn', $self ).text( '登录' ).removeAttr( 'disabled' );
        alert( 'Connection error!' );
      }
    } );
    return false;
  } );

  //获取Cookie
  function getCookie( name ) {
    var arr, reg = new RegExp( '(^| )' + name + '=([^;]*)(;|$)' );
    if ( arr = document.cookie.match( reg ) ) {
      return unescape( arr[ 2 ] );
    } else {
      return null;
    }
  }

  // 未登录的判断
  $( '.js_unlogin_forward' ).on( 'click.js_unlogin_forward', function( e ) {
    // ********************************************************************
    // 未登录的状态需要阻止的操作
    // 事件绑定的函数位置务必放在此函数位置之后且作用域务必小于等于document
    e.preventDefault();
    e.stopImmediatePropagation();
    $( '.modal.in' ).removeClass( 'fade' ).modal( 'hide' ).addClass( 'fade' );
    $self.modal( 'show' );
    returnParam.loginSuccessAndContinue = $.proxy( function() {
      if ( this.tagName.toLowerCase() == 'a' ) {
        if ( $( this ).prop( 'href' ) ) {
          location.href = $( this ).prop( 'href' );
        }
      } else {
        $( this ).trigger( 'click' );
      }
    }, this );
  } );

  return returnParam;
} );
